﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using GatherWebLib;
using GatherWebLib.Model;
using GatherWebLib.publish;
using Novel.BizLogic;
using Novel.Entity;

namespace WebGet_Win
{
    public partial class Frm_Novel : Form
    {
        public Frm_Novel()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<cTask_m> tasks=GetTasks();
            foreach (cTask_m task in tasks)
            {
                if (task.Level > 3)
                {
                    break;
                }
                if (task.Level == 1)
                {
                    GatherAndPublish(task, "", "");
                }
                
                else
                {
                    T_001GatherTaskLogBLLSub log = new T_001GatherTaskLogBLLSub();
                    DataTable dt = log.GetUpdateNovelList();
                    if (dt!=null)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                           
                            string Url=task.WebpageLink[0].Weblink.ToString();
                            if (task.WebpageLink[0].IsChange)
                            {
                                string OldUrl = task.WebpageLink[0].Weblink.ToString();
                                Url = cTool.GetCompleteUrl(dr[task.WebpageLink[0].UrlColName].ToString(), OldUrl);
                            }
                            string bookID = dr["BookID"].ToString();
                            string TableName = dr["TableName"].ToString();
                            task.WebpageLink[0].Weblink = Url;
                            int count=GatherAndPublish(task, TableName, bookID);
                            if (task.Level == 3)
                            {
                                T_005NovelInfoBLLSub bll=new T_005NovelInfoBLLSub();
                                bll.UpdateChapterCount(int.Parse(bookID), count);
                            }
                           

                        }
                    }
                }
            }


           
        }
        DataTable bookes = null;
        private void GetNovelChapter()
        {
            T_001GatherTaskLogBLLSub log = new T_001GatherTaskLogBLLSub();
            DataTable dt = log.GetUpdateNovelList();
            List<cTask_m> tasks = GetTasks();
            if (dt != null)
            {
                  foreach (DataRow dr in dt.Rows)
                  {
                      int taskID = Convert.ToInt32(dr["TaskID"]);
                      int bookID = Convert.ToInt32(dr["BookID"]);
                      string BookName = dr["BookName"].ToString();
                      string ChapterTableName= dr["TableName"].ToString();
                      if (taskID != 0)
                      {
                          cTask_m task = tasks.Find(t => t.TaskID == taskID);

                      }
                      else
                      {
                          List<cTask_m> tasks1 = tasks.FindAll(t => t.Level == 4);
                          if (tasks1 != null && tasks1.Count > 0)
                          {
                              foreach (cTask_m t in tasks1)
                              {
                                  if (bookes == null)
                                  {
                                      bookes = Gather(t);
                                  }

                                DataRow[] book= bookes.Select(string.Format("名称='{0}'", BookName));
                                if (book != null && book.Length > 0)
                                {
                                    string url = book[0]["地址"].ToString();

                                    cTask_m tasks3 = tasks.Find(c => c.FatherID == t.TaskID);
                                    tasks3.WebpageLink[0].Weblink = url;


                                    DataTable ChapterList = Gather(tasks3);

                                    if (ChapterList != null && ChapterList.Rows.Count > 0)
                                    {

                                        string u = cTool.GetCompleteUrl(ChapterList.Rows[0]["地址"].ToString(), url);
                                            cTask_m tasks4 = tasks.Find(c => c.FatherID == tasks3.TaskID);

                                            DataTable ContentList = Gather(tasks4);

                                            foreach (DataRow content in ContentList.Rows)
                                            {
                                                Novel_ChapterBLLSub chbll = new Novel_ChapterBLLSub();
                                                Novel_ChapterEntity chModel = new Novel_ChapterEntity();
                                                chModel.BookID = bookID;
                                                chModel.ChapterTitle = content["标题"].ToString();
                                                chModel.ChapterContent = content["内容"].ToString();
                                                chbll.TableName = ChapterTableName;
                                                chbll.Save(chModel);
                                            }
                                           
                                        
                                        
                                    }

                                }
                              }
                          }

                      }
                  }
            }
        }

        #region
        private DataTable Gather(cTask_m task)
        {
            cGatherTask Gather = new cGatherTask(task);

            Gather.Log += tGather_Log;

            DataTable dt = Gather.Start();
            return dt;
        }

        private int GatherAndPublish(cTask_m task, string tableName, string BookID)
        {
            cGatherTask Gather = new cGatherTask(task);

            Gather.Log += tGather_Log;

            DataTable dt = Gather.Start();
            if (dt == null)
            {
                return 0;
            }
            if (task.TaskRunType == GatherWebLib.cGlobalParas.TaskRunType.GatherExportData && dt.Rows.Count > 0)
            {
                Publish(task.TaskID, dt,tableName,BookID);
            }
            return dt.Rows.Count;
        }

        private List<cTask_m> GetTasks()
        {
            cTask task = new cTask();

            List<cTask_m> list = task.GetTasks(1);
            return list;
        }
        #endregion

        #region 发布数据
        private void Publish(int taskID, DataTable DataSource, string tableName, string BookID)
        {
            cPublishTask publish = new cPublishTask();

            publish.PublishCompleted += this.Publish_Complete;
            publish.PublishError += this.Publish_Error;

            publish.PublishStarted += this.Publish_Started;

            publish.PublishLog += this.Publish_Log;
            publish.m_pTaskData = GetPublishTask(taskID, DataSource);
            string sql=publish.m_pTaskData.Sql;
            if (!string.IsNullOrEmpty(tableName) && sql.Contains("{表名}"))
            {
                sql = sql.Replace("{表名}", tableName);
            }
            if (!string.IsNullOrEmpty(BookID) && sql.Contains("{@BookID}"))
            {
                sql = sql.Replace("{@BookID}", BookID);
            }
            publish.m_pTaskData.Sql = sql;
            publish.startPublic();

        }

        private cPublishTask_m GetPublishTask(int taskID,DataTable DataSource)
        {
            cTask bll = new cTask();
            
            cPublishTask_m pTask = new cPublishTask_m();
            pTask = bll.GetPublishTaskInfo(taskID);
            pTask.PublishData = DataSource;
            return pTask;
        }
        #endregion


        #region 抓取事件
        //写日志事件
        private void tGather_Log(object sender, cGatherTaskLogArgs e)
        {
            //写日志
            string TaskName = e.TaskName;
            string strLog = e.strLog;


            try
            {
                InvokeMethod(this, "ShowInfo", new object[] { e.TaskName, strLog });

            }
            catch (System.Exception ex)
            {
                InvokeMethod(this, "ExportLog", new object[] { DateTime.Now + "：" + ex.Message });
            }

        }
       
        #endregion


        #region 发布任务的事件处理
        private void Publish_Complete(object sender, PublishCompletedEventArgs e)
        {
            InvokeMethod(this, "ShowInfo", new object[] { e.TaskName, "任务成功发布" });


        }

        private void Publish_Started(object sender, PublishStartedEventArgs e)
        {
            InvokeMethod(this, "ShowInfo", new object[] { e.TaskName, "任务开始进行数据发布" });


        }

        private void Publish_Error(object sender, PublishErrorEventArgs e)
        {

            InvokeMethod(this, "ShowInfo", new object[] { e.TaskName, "任务成功失败" });



        }

        private void Publish_Failed(object sender, PublishFailedEventArgs e)
        {

            InvokeMethod(this, "ShowInfo", new object[] { e.TaskName, "任务成功失败" });


        }



        private void Publish_Log(object sender, PublishLogEventArgs e)
        {
            //写发布任务的日志
            Int64 TaskID = e.TaskID;
            string strLog = e.strLog;
            string conName = "sCon" + TaskID;
            string pageName = "page" + TaskID;
        }

        #endregion

        #region 日志
        public void ShowInfo(string Title, string Info)
        {
            ExportLog(DateTime.Now + "：" + "<" + Title + ">    " + Info);
        }
        public void ExportLog(string str)
        {
            try
            {
                cSystemLog sl = new cSystemLog();
                sl.WriteLog(str);
                sl = null;
            }
            catch (System.Exception ex)
            {
                InvokeMethod(this, "ExportLog", new object[] { ex.Message });
            }
        }
        #endregion

        #region 委托代理

        delegate object invokemethod(object Instance, string Method, object[] parameters);

        /// <summary>
        /// 委托执行实例的方法，方法必须都是Public 否则会出错
        /// </summary>
        /// <param name="Instance">类实例</param>
        /// <param name="Method">方法名</param>
        /// <param name="parameters">参数列表</param>
        /// <returns>返回值</returns>
        private object InvokeMethod(object Instance, string Method, object[] parameters)
        {
            if ((bool)GetPropertyValue(Instance, "InvokeRequired"))
            {
                invokemethod d = new invokemethod(InvokeMethod);
                return this.Invoke(d, new object[] { Instance, Method, parameters });
            }
            else
            {
                return MethodInvoke(Instance, Method, parameters);
            }
        }
        /// <summary>
        /// 执行实例的方法
        /// </summary>
        /// <param name="ClassInstance">类实例</param>
        /// <param name="MethodName">方法名</param>
        /// <param name="parameters">参数列表</param>
        /// <returns>返回值</returns>
        private static object MethodInvoke(object ClassInstance, string MethodName, object[] parameters)
        {
            if (parameters == null)
            {
                parameters = new object[0];
            }
            Type myType = ClassInstance.GetType();
            Type[] types = new Type[parameters.Length];
            for (int i = 0; i < parameters.Length; ++i)
            {
                types[i] = parameters[i].GetType();
            }
            MethodInfo myMethodInfo = myType.GetMethod(MethodName, types);
            return myMethodInfo.Invoke(ClassInstance, parameters);
        }
        /// <summary>
        /// 获取实例的属性值
        /// </summary>
        /// <param name="ClassInstance">类实例</param>
        /// <param name="PropertyName">属性名</param>
        /// <returns>属性值</returns>
        private static object GetPropertyValue(object ClassInstance, string PropertyName)
        {
            Type myType = ClassInstance.GetType();
            PropertyInfo myPropertyInfo = myType.GetProperty(PropertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
            return myPropertyInfo.GetValue(ClassInstance, null);
        }
        #endregion

        private void GetTasks(int level)
        {
            cTask task = new cTask();
           List<cTask_m> list=task.GetTasksByLevel(level);
        }

        private void button2_Click(object sender, EventArgs e)
        {
           // GetNovelChapter();
            cTask task = new cTask();
           
            DataTable ContentList = Gather( task.GetTaskInfo(4));

            foreach (DataRow content in ContentList.Rows)
            {
                Novel_ChapterBLLSub chbll = new Novel_ChapterBLLSub();
                Novel_ChapterEntity chModel = new Novel_ChapterEntity();
                chModel.BookID = 1;
                chModel.ChapterTitle = content["标题"].ToString();
                chModel.ChapterContent = content["内容"].ToString();
                chbll.TableName = "T_006Novel_Chapter1";
                chbll.Save(chModel);
            }
        }
    }
}
